#pragma once
 
#include <pthread.h>
#include "ThreadPool.hpp"
#include "Sock.hpp"
#include "Protocol.hpp"

#define PORT 8081
class HttpServer 
{
    private:
        int port;
        int lsock;
        ThreadPool *tp;
        static HttpServer *http_svr;//为了单例模式
        static pthread_mutex_t lock;//为了确保单例模式
        HttpServer()
        {}
        HttpServer(int _p=PORT)
            :port(_p),lsock(-1),tp(nullptr)
        {}
    public:
        static HttpServer * GetInstance(int sk)//为了实现单例模式·
        {
            if(nullptr ==http_svr)
            {
                pthread_mutex_lock(&lock);
                if(nullptr == http_svr)
                {
                    http_svr = new HttpServer(sk);
                }
                pthread_mutex_unlock(&lock);
            }
            return http_svr;
        }
        void InitServer()
        {
            signal(SIGPIPE,SIG_IGN);
            lsock = Sock::Socket();
            Sock::SetSockOpt(lsock);
            Sock::Bind(lsock,port);
            Sock::Listen(lsock);
            tp = new ThreadPool();
            tp->InitThreadPool();
        }
        void Start()
        {
            daemon(1,0);
            for(;;)
            {
                int sock = Sock::Accept(lsock);
                if(sock < 0)
                {
                    continue;
                }
                LOG(Notice,"get a new link...");

                //demo这里创建多线程处理方式
                //pthread_t tid;
                //int *sockp = new int(sock);
                ////这里防止线程刚创建就被cpu挂起，新来的连接会导致现在已存在的失效
                //pthread_create(&tid,nullptr,Entry::HandlerHttp,sockp);
                //pthread_detach(tid);
                
                //demo这里创建线程池处理方式
                Task *tk = new Task(sock);
                tp->PushTask(tk);
            }
        }
        ~HttpServer()
        {
            if(lsock>=0)
            {
                close(lsock);
            }
        }
};
HttpServer *HttpServer::http_svr = nullptr;
pthread_mutex_t HttpServer::lock = PTHREAD_MUTEX_INITIALIZER;

